package com.googlecode.jwsm;

import java.io.IOException;
import java.util.logging.Level;

import javax.servlet.http.*;

import com.googlecode.jwsm.security.*;
import com.googlecode.jwsm.security.SecurityManager;

/**
 * Abstraction layer to log the user in
 * 
 * @author Matthew D. Hicks
 */
public class JWSMSecurity {
	private static SecurityFactory userFactory;
	public static final User getUser(HttpServletRequest request, HttpServletResponse response, boolean redirect) {
		try {
			if (userFactory == null) {
				userFactory = SecurityManager.getSecurityFactory();
			}
			User user = userFactory.login(request, response);
			if ((user == null) && (redirect)) {
				response.sendRedirect("login.jsp");
			}
			return user;
		} catch(SecurityException exc) {
			Log.get().log(Level.FINE, "Security exception attempting to get user", exc);
		} catch(IOException exc) {
			Log.get().log(Level.WARNING, "Exception attempting to get user", exc);
		}
		return null;
	}
	
	public static final void logout(HttpServletRequest request, HttpServletResponse response) throws Exception {
		userFactory.logout(request, response, "login.jsp");
	}
}